#ifndef __BUFF_H__
#define __BUFF_H__
#include <iostream>
#include <vector>
#include <string>
#include <cassert>

namespace ssslog
{
    const int BUFFER_DEFAULT_SIZE = 1024 * 1024 * 100;
    const int BUFFER_INCREMENT_SIZE  = 1024 * 1024 * 1;
    const int BUFFER_THRESHOLD_SIZE  = 10 * 1024 * 1024;
    class Buffer
    {
    public:
        //初始化
        Buffer()
        :_read_idx(0),
        _write_idx(0),
        _buff(BUFFER_DEFAULT_SIZE) {}
        //判空
        bool Empty() { return _write_idx == _read_idx;}
        //读的大小
        size_t ReadBuff() { return _write_idx - _read_idx;}
        //写的大小
        size_t WriteBuff() { return _buff.size() - _write_idx;}
        //初始化
        void Reset() { _write_idx = _read_idx = 0;}
        //交换
        void Swap(Buffer& buff)
        {
            swap(_buff,buff._buff);
           std::swap(_read_idx, buff._read_idx);
            std::swap(_write_idx, buff._write_idx);
        }
        // 插入数据
        void Push(const char* data, size_t size)
        {
            assert(size <= WriteBuff());
            EnsureEnoughSpace(size);
            std::copy(data,data+size,&_buff[_write_idx]);
            _write_idx += size;
        }
        // 开始位置
        const char* Begin() { return &_buff[_read_idx]; }
        // 删除数据
        void Pop(size_t size)
        {
            _read_idx += size;
            assert(_read_idx <= _write_idx);
        }
        
    private:
        // 确保具有足够空间
        void EnsureEnoughSpace(size_t size)
        {
            assert(size > 0);
            if(size < WriteBuff()) return;
            size_t new_capacity = 0;
            if (_buff.size() < BUFFER_THRESHOLD_SIZE)
                new_capacity = _buff.size() * 2 + size; // 
            else
                new_capacity = _buff.size() + BUFFER_INCREMENT_SIZE + size; //
            _buff.resize(new_capacity);
        }
    private:
        size_t _read_idx; //读
        size_t _write_idx; //写
        std::vector<char> _buff; 
    };
}
#endif 